#include "../include/acceptor.h"
#include <stdio.h>

Acceptor::Acceptor(const string & ip,unsigned short port)
:_socket()
,_addr(ip,port)
{


}

Acceptor::~Acceptor()
{

}

void Acceptor::ready()
{
	setReuseAddr();
	
	setReusePort();

	bind();

	listen();
}

void Acceptor::setReuseAddr()
{
	int on = 1;
	int ret = setsockopt(_socket.fd(),SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
	if(ret)
	{
		perror("setsockopt error");
		return;
	}
}

void Acceptor::setReusePort()
{
	int on = 1;
	int ret = setsockopt(_socket.fd(),SOL_SOCKET,SO_REUSEPORT,&on,sizeof(on));
	if(ret == -1)
	{
		perror("setsockopt error");
		return;
	}
}

void Acceptor::bind()
{
	int ret = ::bind(_socket.fd(),(struct sockaddr *)_addr.getInetAddrPtr(),sizeof(struct sockaddr ));
	if(ret == -1)
	{
		perror("bind error");
		return ;
	}
}

void Acceptor::listen()
{
	int ret = ::listen(_socket.fd(),128);
	if(ret == -1)
	{
		perror("listen error");
		return ;
	}
}

int Acceptor::fd() const
{
	return _socket.fd();
}

int Acceptor::accept()
{
	int conFd = ::accept(_socket.fd(),nullptr,nullptr);
	if(conFd == -1)
	{
		perror("accept error");
		return -1;
	}
	return conFd;
}




